<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>安全管理 - CRUD Generator</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css" rel="stylesheet">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- Common CSS -->
    <link href="/css/common.css" rel="stylesheet">
    
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background: #f8f9fa;
            padding-top: 80px;
        }
        
        .navbar {
            background: white !important;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            position: fixed;
            top: 0;
            width: 100%;
            z-index: 1000;
        }
        
        .main-content {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .page-header {
            background: linear-gradient(135deg, #dc3545 0%, #e83e8c 100%);
            color: white;
            border-radius: 20px;
            padding: 40px;
            margin-bottom: 30px;
            text-align: center;
        }
        
        .security-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            overflow: hidden;
            margin-bottom: 30px;
        }
        
        .security-header {
            background: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
            padding: 20px 25px;
            font-weight: 600;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .security-body {
            padding: 25px;
        }
        
        .security-status {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 20px;
        }
        
        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            display: inline-block;
        }
        
        .status-secure {
            background: #28a745;
        }
        
        .status-warning {
            background: #ffc107;
        }
        
        .status-danger {
            background: #dc3545;
        }
        
        .user-table {
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            overflow: hidden;
        }
        
        .role-badge {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 500;
        }
        
        .role-admin {
            background: #dc3545;
            color: white;
        }
        
        .role-user {
            background: #28a745;
            color: white;
        }
        
        .role-guest {
            background: #6c757d;
            color: white;
        }
        
        .permission-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
        }
        
        .permission-item {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            text-align: center;
            transition: all 0.3s ease;
        }
        
        .permission-item:hover {
            background: #e9ecef;
        }
        
        .permission-icon {
            font-size: 2rem;
            margin-bottom: 10px;
            color: #667eea;
        }
        
        .audit-log {
            max-height: 400px;
            overflow-y: auto;
        }
        
        .log-entry {
            border-left: 4px solid #e9ecef;
            padding: 15px;
            margin-bottom: 10px;
            background: #f8f9fa;
            border-radius: 0 10px 10px 0;
        }
        
        .log-entry.success {
            border-left-color: #28a745;
        }
        
        .log-entry.warning {
            border-left-color: #ffc107;
        }
        
        .log-entry.danger {
            border-left-color: #dc3545;
        }
        
        .log-time {
            font-size: 0.8rem;
            color: #6c757d;
        }
        
        .security-metric {
            text-align: center;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 10px;
            margin-bottom: 15px;
        }
        
        .metric-value {
            font-size: 2rem;
            font-weight: 700;
            color: #2d3748;
        }
        
        .metric-label {
            color: #6c757d;
            font-size: 0.9rem;
        }
        
        .threat-alert {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .threat-alert.high {
            background: #f8d7da;
            border-color: #f5c6cb;
        }
        
        .threat-alert.medium {
            background: #fff3cd;
            border-color: #ffeaa7;
        }
        
        .threat-alert.low {
            background: #d1ecf1;
            border-color: #bee5eb;
        }
        
        .action-btn {
            padding: 8px 16px;
            border-radius: 8px;
            border: none;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .btn-secure {
            background: #28a745;
            color: white;
        }
        
        .btn-secure:hover {
            background: #218838;
            color: white;
        }
        
        .btn-warning {
            background: #ffc107;
            color: #212529;
        }
        
        .btn-warning:hover {
            background: #e0a800;
            color: #212529;
        }
        
        .btn-danger {
            background: #dc3545;
            color: white;
        }
        
        .btn-danger:hover {
            background: #c82333;
            color: white;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <div th:replace="fragments/navigation :: navbar"></div>

    <div class="main-content">
        <!-- Page Header -->
        <div class="page-header">
            <h1 class="display-5 mb-3">
                <i class="bi bi-shield-check me-3"></i>
                安全管理中心
            </h1>
            <p class="lead mb-0">系统安全监控、用户权限管理和威胁防护</p>
        </div>

        <!-- Security Overview -->
        <div class="row mb-4">
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="security-metric">
                    <div class="metric-value text-success">98.5%</div>
                    <div class="metric-label">安全评分</div>
                </div>
            </div>
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="security-metric">
                    <div class="metric-value text-warning">3</div>
                    <div class="metric-label">待处理威胁</div>
                </div>
            </div>
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="security-metric">
                    <div class="metric-value text-info">156</div>
                    <div class="metric-label">活跃用户</div>
                </div>
            </div>
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="security-metric">
                    <div class="metric-value text-primary">24h</div>
                    <div class="metric-label">上次扫描</div>
                </div>
            </div>
        </div>

        <!-- Threat Alerts -->
        <div class="threat-alert medium">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h6 class="mb-1">
                        <i class="bi bi-exclamation-triangle me-2"></i>
                        检测到异常登录尝试
                    </h6>
                    <small class="text-muted">来自IP: 192.168.1.100 的多次失败登录</small>
                </div>
                <button class="btn btn-warning btn-sm" onclick="handleThreat('login-attempt')">
                    处理威胁
                </button>
            </div>
        </div>

        <div class="row">
            <!-- User Management -->
            <div class="col-lg-8">
                <div class="security-card">
                    <div class="security-header">
                        <h5 class="mb-0">
                            <i class="bi bi-people me-2"></i>用户权限管理
                        </h5>
                        <button class="btn btn-primary btn-sm" onclick="addUser()">
                            <i class="bi bi-plus me-1"></i>添加用户
                        </button>
                    </div>
                    <div class="security-body">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>用户名</th>
                                        <th>角色</th>
                                        <th>最后登录</th>
                                        <th>状态</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="usersTable">
                                    <tr>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="avatar me-3">
                                                    <i class="bi bi-person-circle fs-4"></i>
                                                </div>
                                                <div>
                                                    <strong>admin</strong>
                                                    <br>
                                                    <small class="text-muted">admin@example.com</small>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <span class="role-badge role-admin">管理员</span>
                                        </td>
                                        <td>2024-01-15 14:30</td>
                                        <td>
                                            <span class="status-indicator status-secure"></span>
                                            在线
                                        </td>
                                        <td>
                                            <button class="btn btn-sm btn-outline-primary" onclick="editUser('admin')">
                                                <i class="bi bi-pencil"></i>
                                            </button>
                                            <button class="btn btn-sm btn-outline-danger" onclick="suspendUser('admin')">
                                                <i class="bi bi-ban"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="avatar me-3">
                                                    <i class="bi bi-person-circle fs-4"></i>
                                                </div>
                                                <div>
                                                    <strong>developer</strong>
                                                    <br>
                                                    <small class="text-muted">dev@example.com</small>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <span class="role-badge role-user">开发者</span>
                                        </td>
                                        <td>2024-01-15 12:15</td>
                                        <td>
                                            <span class="status-indicator status-warning"></span>
                                            离线
                                        </td>
                                        <td>
                                            <button class="btn btn-sm btn-outline-primary" onclick="editUser('developer')">
                                                <i class="bi bi-pencil"></i>
                                            </button>
                                            <button class="btn btn-sm btn-outline-danger" onclick="suspendUser('developer')">
                                                <i class="bi bi-ban"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="avatar me-3">
                                                    <i class="bi bi-person-circle fs-4"></i>
                                                </div>
                                                <div>
                                                    <strong>guest</strong>
                                                    <br>
                                                    <small class="text-muted">guest@example.com</small>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <span class="role-badge role-guest">访客</span>
                                        </td>
                                        <td>2024-01-14 16:45</td>
                                        <td>
                                            <span class="status-indicator status-danger"></span>
                                            已禁用
                                        </td>
                                        <td>
                                            <button class="btn btn-sm btn-outline-primary" onclick="editUser('guest')">
                                                <i class="bi bi-pencil"></i>
                                            </button>
                                            <button class="btn btn-sm btn-outline-success" onclick="enableUser('guest')">
                                                <i class="bi bi-check"></i>
                                            </button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Security Status -->
            <div class="col-lg-4">
                <div class="security-card">
                    <div class="security-header">
                        <h5 class="mb-0">
                            <i class="bi bi-shield-check me-2"></i>安全状态
                        </h5>
                    </div>
                    <div class="security-body">
                        <div class="security-status">
                            <span class="status-indicator status-secure"></span>
                            <strong>防火墙: 已启用</strong>
                        </div>
                        <div class="security-status">
                            <span class="status-indicator status-secure"></span>
                            <strong>SSL证书: 有效</strong>
                        </div>
                        <div class="security-status">
                            <span class="status-indicator status-warning"></span>
                            <strong>密码策略: 需要更新</strong>
                        </div>
                        <div class="security-status">
                            <span class="status-indicator status-secure"></span>
                            <strong>双因子认证: 已启用</strong>
                        </div>
                        <div class="security-status">
                            <span class="status-indicator status-danger"></span>
                            <strong>入侵检测: 发现威胁</strong>
                        </div>
                        
                        <hr>
                        
                        <h6>权限模块</h6>
                        <div class="permission-grid">
                            <div class="permission-item">
                                <div class="permission-icon">
                                    <i class="bi bi-code"></i>
                                </div>
                                <small>代码生成</small>
                            </div>

                            <div class="permission-item">
                                <div class="permission-icon">
                                    <i class="bi bi-file-earmark-code"></i>
                                </div>
                                <small>智能合约</small>
                            </div>
                            <div class="permission-item">
                                <div class="permission-icon">
                                    <i class="bi bi-gear"></i>
                                </div>
                                <small>系统设置</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Audit Log -->
        <div class="security-card">
            <div class="security-header">
                <h5 class="mb-0">
                    <i class="bi bi-journal-text me-2"></i>安全审计日志
                </h5>
                <div class="d-flex gap-2">
                    <select class="form-select form-select-sm" style="width: auto;" id="logFilter">
                        <option value="all">所有日志</option>
                        <option value="success">成功操作</option>
                        <option value="warning">警告事件</option>
                        <option value="danger">安全威胁</option>
                    </select>
                    <button class="btn btn-outline-primary btn-sm" onclick="exportLogs()">
                        <i class="bi bi-download me-1"></i>导出
                    </button>
                </div>
            </div>
            <div class="security-body">
                <div class="audit-log" id="auditLog">
                    <div class="log-entry success">
                        <div class="d-flex justify-content-between">
                            <div>
                                <strong>用户登录成功</strong>
                                <br>
                                <small>用户 admin 从 192.168.1.10 成功登录</small>
                            </div>
                            <div class="log-time">2024-01-15 14:30:25</div>
                        </div>
                    </div>
                    
                    <div class="log-entry warning">
                        <div class="d-flex justify-content-between">
                            <div>
                                <strong>密码策略违规</strong>
                                <br>
                                <small>用户 developer 尝试设置弱密码</small>
                            </div>
                            <div class="log-time">2024-01-15 13:45:12</div>
                        </div>
                    </div>
                    
                    <div class="log-entry danger">
                        <div class="d-flex justify-content-between">
                            <div>
                                <strong>异常登录尝试</strong>
                                <br>
                                <small>来自 192.168.1.100 的多次失败登录尝试</small>
                            </div>
                            <div class="log-time">2024-01-15 12:30:45</div>
                        </div>
                    </div>
                    
                    <div class="log-entry success">
                        <div class="d-flex justify-content-between">
                            <div>
                                <strong>权限更新</strong>
                                <br>
                                <small>管理员更新了用户 guest 的权限设置</small>
                            </div>
                            <div class="log-time">2024-01-15 11:15:30</div>
                        </div>
                    </div>
                    
                    <div class="log-entry warning">
                        <div class="d-flex justify-content-between">
                            <div>
                                <strong>SSL证书即将过期</strong>
                                <br>
                                <small>SSL证书将在30天后过期，请及时更新</small>
                            </div>
                            <div class="log-time">2024-01-15 10:00:00</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- Common JS -->
    <script src="/js/common.js"></script>

    <script>
        // Sample security data
        const securityData = {
            users: [
                { username: 'admin', email: 'admin@example.com', role: 'admin', lastLogin: '2024-01-15 14:30', status: 'online' },
                { username: 'developer', email: 'dev@example.com', role: 'user', lastLogin: '2024-01-15 12:15', status: 'offline' },
                { username: 'guest', email: 'guest@example.com', role: 'guest', lastLogin: '2024-01-14 16:45', status: 'disabled' }
            ],
            threats: [
                { id: 'login-attempt', type: 'medium', message: '检测到异常登录尝试', details: '来自IP: 192.168.1.100 的多次失败登录' },
                { id: 'ssl-expiry', type: 'low', message: 'SSL证书即将过期', details: 'SSL证书将在30天后过期' },
                { id: 'weak-password', type: 'medium', message: '发现弱密码', details: '用户 developer 使用了弱密码' }
            ]
        };

        // Initialize page
        document.addEventListener('DOMContentLoaded', function() {
            loadSecurityStatus();
            setupLogFilter();
            startSecurityMonitoring();
        });

        function loadSecurityStatus() {
            // Update security metrics with animation
            animateCounter('.metric-value', 2000);
        }

        function setupLogFilter() {
            document.getElementById('logFilter').addEventListener('change', function() {
                filterAuditLogs(this.value);
            });
        }

        function filterAuditLogs(type) {
            const logs = document.querySelectorAll('.log-entry');
            logs.forEach(log => {
                if (type === 'all' || log.classList.contains(type)) {
                    log.style.display = 'block';
                } else {
                    log.style.display = 'none';
                }
            });
        }

        function runSecurityScan() {
            Utils.showLoading();
            
            setTimeout(() => {
                Utils.hideLoading();
                
                // Simulate security scan results
                const threats = Math.floor(Math.random() * 5);
                const score = (95 + Math.random() * 5).toFixed(1);
                
                Utils.showToast(`安全扫描完成！发现 ${threats} 个威胁，安全评分: ${score}%`, 
                    threats > 2 ? 'warning' : 'success');
                
                // Update metrics
                document.querySelector('.metric-value.text-success').textContent = score + '%';
                document.querySelector('.metric-value.text-warning').textContent = threats;
            }, 3000);
        }

        function lockdownSystem() {
            Utils.showConfirm('确定要锁定系统吗？这将阻止所有非管理员用户访问。', function(confirmed) {
                if (confirmed) {
                    Utils.showLoading();
                    
                    setTimeout(() => {
                        Utils.hideLoading();
                        Utils.showToast('系统已进入锁定模式', 'warning');
                        
                        // Update UI to show lockdown state
                        document.body.style.filter = 'grayscale(50%)';
                        
                        // Add lockdown banner
                        const banner = document.createElement('div');
                        banner.className = 'alert alert-danger position-fixed top-0 start-0 end-0';
                        banner.style.zIndex = '9999';
                        banner.innerHTML = '<i class="bi bi-lock me-2"></i>系统已锁定 - 仅管理员可访问';
                        document.body.prepend(banner);
                    }, 2000);
                }
            });
        }

        function handleThreat(threatId) {
            const threat = securityData.threats.find(t => t.id === threatId);
            if (threat) {
                Utils.showConfirm(`确定要处理威胁: ${threat.message}？`, function(confirmed) {
                    if (confirmed) {
                        Utils.showLoading();
                        
                        setTimeout(() => {
                            Utils.hideLoading();
                            Utils.showToast('威胁已处理', 'success');
                            
                            // Remove threat alert
                            document.querySelector('.threat-alert').style.display = 'none';
                            
                            // Update threat count
                            const threatCount = document.querySelector('.metric-value.text-warning');
                            threatCount.textContent = parseInt(threatCount.textContent) - 1;
                        }, 1500);
                    }
                });
            }
        }

        function addUser() {
            Utils.showToast('打开添加用户对话框', 'info');
            // Here you would typically open a modal or navigate to a user creation form
        }

        function editUser(username) {
            Utils.showToast(`编辑用户: ${username}`, 'info');
            // Here you would typically open an edit modal with user details
        }

        function suspendUser(username) {
            Utils.showConfirm(`确定要暂停用户 ${username} 吗？`, function(confirmed) {
                if (confirmed) {
                    Utils.showToast(`用户 ${username} 已被暂停`, 'warning');
                    // Update user status in the table
                }
            });
        }

        function enableUser(username) {
            Utils.showConfirm(`确定要启用用户 ${username} 吗？`, function(confirmed) {
                if (confirmed) {
                    Utils.showToast(`用户 ${username} 已被启用`, 'success');
                    // Update user status in the table
                }
            });
        }

        function exportLogs() {
            Utils.showLoading();
            
            setTimeout(() => {
                Utils.hideLoading();
                
                // Simulate log export
                const logs = document.querySelectorAll('.log-entry:not([style*="display: none"])');
                const logData = Array.from(logs).map(log => ({
                    timestamp: log.querySelector('.log-time').textContent,
                    event: log.querySelector('strong').textContent,
                    details: log.querySelector('small').textContent,
                    level: log.classList.contains('success') ? 'success' : 
                           log.classList.contains('warning') ? 'warning' : 'danger'
                }));
                
                const blob = new Blob([JSON.stringify(logData, null, 2)], { type: 'application/json' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `security-logs-${new Date().toISOString().split('T')[0]}.json`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                
                Utils.showToast('安全日志已导出', 'success');
            }, 1500);
        }

        function startSecurityMonitoring() {
            // Simulate real-time security monitoring
            setInterval(() => {
                // Randomly update some metrics
                if (Math.random() < 0.1) { // 10% chance every interval
                    const events = ['用户登录', '权限检查', '数据访问', '系统扫描'];
                    const event = events[Math.floor(Math.random() * events.length)];
                    
                    // Add new log entry (in a real app, this would come from the server)
                    console.log(`新的安全事件: ${event}`);
                }
            }, 5000); // Check every 5 seconds
        }

        function animateCounter(selector, duration) {
            const elements = document.querySelectorAll(selector);
            elements.forEach(element => {
                const target = parseFloat(element.textContent);
                let current = 0;
                const increment = target / (duration / 50);
                
                const timer = setInterval(() => {
                    current += increment;
                    if (current >= target) {
                        current = target;
                        clearInterval(timer);
                    }
                    
                    if (element.textContent.includes('%')) {
                        element.textContent = current.toFixed(1) + '%';
                    } else if (element.textContent.includes('h')) {
                        element.textContent = Math.floor(current) + 'h';
                    } else {
                        element.textContent = Math.floor(current);
                    }
                }, 50);
            });
        }
    </script>
</body>
</html>